<template>
  <Dialog title="设定" v-model="dialogVisible" :width="500">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-form-item label="公司" prop="companyId">
        <el-select
          v-model="formData.companyId"
          placeholder="请选择公司"
          filterable
          @change="handleCompanyChange"
        >
          <el-option
            v-for="company in companyList"
            :key="company.id"
            :label="company.name"
            :value="company.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="招聘职位" prop="companyRequirementId">
        <el-select
          v-model="formData.companyRequirementId"
          placeholder="请选择招聘职位"
          filterable
          @change="handlePositionChange"
        >
          <el-option
            v-for="position in positionList"
            :key="position.id"
            :label="getPositionLabel(position)"
            :value="position.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="角色设定" prop="systemMessage">
        <el-input
          type="textarea"
          v-model="formData.systemMessage"
          :rows="4"
          placeholder="请输入角色设定，例如：我是HR，岗位要求：1.Java基础扎实，理解IO、线程、集合等。2. ....."
        />
      </el-form-item>
      <el-form-item label="模型" prop="modelId">
        <el-select v-model="formData.modelId" placeholder="请选择模型">
          <el-option
            v-for="model in models"
            :key="model.id"
            :label="model.name"
            :value="model.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="温度参数" prop="temperature">
        <el-input-number
          v-model="formData.temperature"
          placeholder="请输入温度参数"
          :min="0"
          :max="2"
          :precision="2"
          class="!w-1/1"
        />
      </el-form-item> -->
      <el-form-item label="回复数 Token 数" prop="maxTokens">
        <el-input-number
          v-model="formData.maxTokens"
          placeholder="请输入回复数 Token 数"
          :min="0"
          :max="8192"
          class="!w-1/1"
        />
      </el-form-item>
      <el-form-item label="上下文数量" prop="maxContexts">
        <el-input-number
          v-model="formData.maxContexts"
          placeholder="请输入上下文数量"
          :min="0"
          :max="20"
          class="!w-1/1"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ModelApi, ModelVO } from '@/api/ai/model/model'
import { ChatConversationApi, ChatConversationVO } from '@/api/ai/chat/conversation'
import { AiModelTypeEnum } from '@/views/ai/utils/constants'
import { CompanyApi, CompanyVO } from '@/api/system/company'
import { getDictDataPage, DictDataVO } from '@/api/system/dict/dict.data'
import { CompanyRequirementApi, CompanyRequirementVO } from '@/api/system/companyrequirement'

/** AI 聊天对话的更新表单 */
defineOptions({ name: 'ChatConversationUpdateForm' })

const message = useMessage() // 消息弹窗

// 定义表单数据类型
interface FormDataType {
  id?: number
  systemMessage?: string
  modelId?: number
  temperature?: number
  maxTokens?: number
  maxContexts?: number
  companyId?: number
  companyRequirementId?: number
}

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<FormDataType>({
  id: undefined,
  systemMessage: undefined,
  modelId: undefined,
  temperature: undefined,
  maxTokens: undefined,
  maxContexts: undefined,
  companyId: undefined,
  companyRequirementId: undefined
})
const formRules = reactive({
  systemMessage: [{ required: true, message: '角色设定不能为空', trigger: 'blur' }],
  modelId: [{ required: true, message: '模型不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  // temperature: [{ required: true, message: '温度参数不能为空', trigger: 'blur' }],
  maxTokens: [{ required: true, message: '回复数 Token 数不能为空', trigger: 'blur' }],
  maxContexts: [{ required: true, message: '上下文数量不能为空', trigger: 'blur' }],
  companyId: [{ required: true, message: '公司不能为空', trigger: 'change' }],
  companyRequirementId: [{ required: true, message: '招聘职位不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const models = ref([] as ModelVO[]) // 聊天模型列表
const companyList = ref<CompanyVO[]>([]) // 公司列表
const positionList = ref<CompanyRequirementVO[]>([]) // 公司职位需求列表
const dictList = ref<DictDataVO[]>([]) // 职位字典列表

// 获取公司列表
const getCompanyList = async () => {
  try {
    const res = await CompanyApi.getCompanyPage({
      pageNo: 1,
      pageSize: 100
    })
    companyList.value = res.list || []
  } catch (error) {
    console.error('获取公司列表失败', error)
    message.error('获取公司列表失败')
  }
}

// 获取职位字典列表
const getDictList = async () => {
  try {
    // 定义完整参数对象，避免类型问题
    const params: any = {
      pageNo: 1,
      pageSize: 100,
      dictType: 'system_requirement'
    }
    const res = await getDictDataPage(params)
    dictList.value = res.list || []
  } catch (error) {
    console.error('获取职位字典列表失败', error)
    message.error('获取职位字典列表失败')
  }
}

// 获取公司职位需求列表
const getCompanyRequirementList = async (companyId: number) => {
  try {
    const res = await CompanyRequirementApi.getCompanyRequirementPage({
      pageNo: 1,
      pageSize: 100,
      companyId: companyId
    })
    positionList.value = res.list || []
  } catch (error) {
    console.error('获取公司职位需求列表失败', error)
    message.error('获取公司职位需求列表失败')
  }
}

// 处理公司变更
const handleCompanyChange = async () => {
  // 重置招聘职位
  formData.value.companyRequirementId = undefined

  // 如果选择了公司，则获取该公司的职位需求列表
  if (formData.value.companyId) {
    await getCompanyRequirementList(formData.value.companyId)
  } else {
    positionList.value = []
  }
}

// 处理职位变更
const handlePositionChange = () => {
  // 根据职位ID查找对应的职位详情
  if (!formData.value.companyRequirementId) return

  const selectedPosition = positionList.value.find(
    (item) => item.id === formData.value.companyRequirementId
  )
  if (selectedPosition) {
    // 使用职位的focus字段作为角色设定
    formData.value.systemMessage = selectedPosition.focus || ''
  }
}

// 获取职位显示名称（根据type查找对应的字典项的label）
const getPositionLabel = (position: CompanyRequirementVO): string => {
  const dictItem = dictList.value.find((item) => parseInt(item.value) === position.type)
  return dictItem ? `${dictItem.label} (${position.remark || ''})` : `类型: ${position.type}`
}

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  resetForm()

  // 加载公司和字典列表
  formLoading.value = true
  try {
    await Promise.all([getCompanyList(), getDictList()])

    // 修改时，设置数据
    if (id) {
      const data = await ChatConversationApi.getChatConversationMy(id)
      // 更新表单数据
      formData.value.id = data.id
      formData.value.systemMessage = data.systemMessage
      formData.value.modelId = data.modelId
      formData.value.temperature = data.temperature
      formData.value.maxTokens = data.maxTokens
      formData.value.maxContexts = data.maxContexts
      formData.value.companyId = data.companyId
      formData.value.companyRequirementId = data.companyRequirementId

      // 如果有公司ID，加载该公司的职位需求
      if (data.companyId) {
        await getCompanyRequirementList(data.companyId)
      }
    }
  } finally {
    formLoading.value = false
  }
  // 获得下拉数据
  models.value = await ModelApi.getModelSimpleList(AiModelTypeEnum.CHAT)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  try {
    await formRef.value.validate()

    // 额外检查必填项
    if (!formData.value.companyId) {
      message.error('请选择公司')
      return
    }

    if (!formData.value.companyRequirementId) {
      message.error('请选择招聘职位')
      return
    }

    if (!formData.value.systemMessage) {
      message.error('请填写角色设定')
      return
    }

    // 提交请求
    formLoading.value = true
    try {
      const data = formData.value as unknown as ChatConversationVO
      await ChatConversationApi.updateChatConversationMy(data)
      message.success('对话配置已更新')
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  } catch (error) {
    console.error('表单验证失败', error)
    message.error('表单验证失败，请检查必填项')
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    systemMessage: undefined,
    modelId: undefined,
    temperature: undefined,
    maxTokens: undefined,
    maxContexts: undefined,
    companyId: undefined,
    companyRequirementId: undefined
  }
  formRef.value?.resetFields()
}
</script>
